<template>

  <ul class="tools">
    <li>
      <van-icon name="arrow-left" size="30" @click="router.push('/')" />
    </li>
    <li>
      <van-icon name="comment-o" size="30" @click="showComments" /> {{ comments }}
    </li>
    <li><van-icon name="good-job-o" size="30" /> {{ popularity }}</li>
    <li><van-icon name="star-o" size="30" /></li>
    <li><van-icon name="share-o" size="30" @click="showShare = true" /></li>
  </ul>

  <van-share-sheet v-model:show="showShare" title="立即分享给好友" :options="options" :description="articleTitle"
    @select="onSelect" />

  <van-dialog v-model:show="showQRCode" title="分享二维码">
    <img :src="qrCodeUrl" alt="QR Code" style="width: 100%; height: auto;" />
  </van-dialog>


  <van-dialog v-model:show="showPoster" title="分享海报">
    <img :src="posterUrl" alt="Poster" style="width: 100%; height: 200px;" />
    <van-button type="primary" block @click="downloadPoster" class="download-button">下载海报</van-button>
  </van-dialog>

  <!-- 海报内容 -->
  <div ref="posterContent" class="poster-content" v-show="isPosterContentVisible">
    <img :src="imageUrl" alt="Article Image" class="poster-image" />
    <div class="poster-title">{{ articleTitle }}</div>
    <!-- <div class="poster-link">{{ currentUrl }}</div> -->
  </div>

</template>


<script setup>
import QRCode from 'qrcode'
import html2canvas from 'html2canvas'

import { getDailyExtra } from "@/api/index.js"
import { onMounted, ref, computed, nextTick, useTemplateRef } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { showToast } from 'vant'
const route = useRoute()
const router = useRouter()

const posterContent = useTemplateRef('posterContent')

// const props = defineProps({
//   articleTitle: {
//     type: String,
//   },
//   articleImage: {
//     type: String,
//   },
//   shareContent:{
//     type: String,
//   }
// })

const props = defineProps(['articleTitle', 'articleImage'])


const articleTitle = computed(() => props.articleTitle)
const articleImage = computed(() => props.articleImage)


const showShare = ref(false);
const showQRCode = ref(false);
const qrCodeUrl = ref('');
const showPoster = ref(false);
const posterUrl = ref('');
const currentUrl = computed(() => route.fullPath)
const isPosterContentVisible = ref(false);

// 在图片URL后添加时间戳避免缓存问题
const timestamp = new Date().getTime();



// const imageUrl = `${articleImage.value}?timestamp=${timestamp}`;

const imageUrl = computed(() => `${articleImage.value}?timestamp=${timestamp}`)



const options = [
  { name: '微信', icon: 'wechat' },
  { name: '微博', icon: 'weibo' },
  { name: '复制链接', icon: 'link' },
  { name: '分享海报', icon: 'poster' },
  { name: '二维码', icon: 'qrcode' },
];

const onSelect = async (option, index) => {
  switch (option.name) {
    case '微信':
      shareToWeChat();
      break;
    case '微博':
      shareToWeibo();
      break;
    case '复制链接':
      copyLink();
      break;
    case '分享海报':
      sharePoster();
      break;
    case '二维码':
      generateQRCode();
      break;
    default:
      break;
  }
  showShare.value = false;
};


const articleId = ref(route.params.articleId)




const comments = ref(0)
const popularity = ref(0)

onMounted(async () => {
  const response = await getDailyExtra(articleId.value)

  comments.value = response.comments
  popularity.value = response.popularity
});

const showComments = () => {
  router.push({ path: `/article/${articleId.value}/comments` })
};


//分享相关的API
const shareToWeChat = () => {
  // 使用微信JS-SDK实现分享功能
  console.log('分享到微信');
  // 这里需要配置微信JS-SDK，并调用相应的分享接口
};

const shareToWeibo = () => {
  // 使用微博分享接口
  const url = `https://service.weibo.com/share/share.php?url=${encodeURIComponent(currentUrl.value)}&title=${encodeURIComponent(props.articleTitle)}`
  window.open(url, '_blank');
};

const copyLink = () => {
  navigator.clipboard.writeText(currentUrl.value).then(() => {
    // console.log('链接已复制到剪贴板');
    showToast('链接已复制');
  }).catch(err => {
    console.error('无法复制链接: ', err);
  });
};

// 获取设备的像素比
const devicePixelRatio = window.devicePixelRatio || 1;

const sharePoster = async () => {
  try {
    isPosterContentVisible.value = true;
    await nextTick();

    // 预加载所有图片
    const images = Array.from(posterContent.value.querySelectorAll('img'));
    await Promise.all(images.map(img => {
      return new Promise((resolve) => {
        const newImg = new Image();
        newImg.crossOrigin = 'Anonymous';
        newImg.src = img.src + '?t=' + Date.now();
        newImg.onload = resolve;
        newImg.onerror = resolve;
      })
    }));

    // 强制同步布局
    const rect = posterContent.value.getBoundingClientRect();

    const canvas = await html2canvas(posterContent.value, {
      scale: 2, // 调整为3倍缩放
      useCORS: true,
      backgroundColor: '#ffffff',
      logging: true,
      allowTaint: false,
      onclone: (clonedDoc) => {
        // 克隆节点时保持样式一致性
        clonedDoc.querySelector('.poster-content').style.visibility = 'visible';
      }
    });

    // 质量优化处理
    const ctx = canvas.getContext('2d');
    ctx.imageSmoothingEnabled = true;
    ctx.imageSmoothingQuality = 'high';

    posterUrl.value = canvas.toDataURL('image/png', { quality: 0.95 });
    showPoster.value = true;
  } catch (error) {
    console.error('生成海报失败:', error);
    showToast('生成失败，请重试');
  } finally {
    isPosterContentVisible.value = false;
  }
};

const downloadPoster = () => {
  const link = document.createElement('a');
  link.href = posterUrl.value;
  link.download = 'article-poster.png';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  showPoster.value = false;
};

const generateQRCode = async () => {
  try {
    qrCodeUrl.value = await QRCode.toDataURL(currentUrl.value);
    showQRCode.value = true;
  } catch (error) {
    console.error('生成二维码失败: ', error);
  }
};


</script>

<style scoped>
.tools {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  overflow: hidden;
  list-style: none;
  margin: 0;
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  grid-gap: 10px;
  background-color: #f9f9f9;
  padding: 5px 0;
  text-align: center;
  align-items: center;
  height: 50px;
}

.tools li:first-child {
  border-right: 1px solid #ddd;
}


:deep(.van-icon) {
  cursor: pointer;
}



.download-button {
  margin: 0 auto;
}


:deep(.van-dialog__content) {
  text-align: center;
}


/** 修改后的海报样式 */
.poster-content {
  position: fixed;
  left: -9999px;
  /* width: 375px; */

  /* 固定设计稿宽度 */
  /* min-height: 667px; */
  /* 固定设计稿高度 */
  background: white;
  padding: 10px;
  box-sizing: border-box;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center
}

.poster-image {
  /* width: 100%; */
  height: 120px;
  /* 固定图片高度 */
  object-fit: cover;
  /* 保持图片比例 */
  border-radius: 8px;
  margin-bottom: 15px;
}

.poster-title {
  font-size: 14px;
  /* 适当增大字号 */
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
  line-height: 1.4;
  font-family: 'PingFang SC', system-ui;
  /* 指定中文字体 */
  transform: translateZ(0);
  -webkit-font-smoothing: antialiased;
  /* 字体抗锯齿 */
  /* 启用硬件加速 */
}

.poster-link {
  position: absolute;
  bottom: 20px;
  font-size: 12px;
  color: #666;
  word-break: break-all;
  padding: 0 10px;
}
</style>
